from machine import I2C, Pin
import time

# SGP30 的 I2C 地址
SGP30_I2C_ADDR = 0x58

# 初始化 I2C
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=100000)

# SGP30 初始化命令
def sgp30_init():
    i2c.writeto(SGP30_I2C_ADDR, bytearray([0x20, 0x03]))

# 读取 SGP30 数据
def sgp30_read():
    # 发送测量命令
    i2c.writeto(SGP30_I2C_ADDR, bytearray([0x20, 0x08]))
    time.sleep_ms(12)  # 等待测量完成

    # 读取 6 字节数据（eCO₂ 和 TVOC）
    data = i2c.readfrom(SGP30_I2C_ADDR, 6)
    
    # 解析 eCO₂ 和 TVOC 值
    eco2 = (data[0] << 8) | data[1]
    tvoc = (data[3] << 8) | data[4]
    
    return eco2, tvoc

# 主程序
def main():
    sgp30_init()  # 初始化 SGP30
    time.sleep_ms(500)  # 等待初始化完成

    while True:
        eco2, tvoc = sgp30_read()
        print("eCO2: {} ppm, TVOC: {} ppb".format(eco2*1.96, tvoc *0.0041))
        time.sleep(1)  # 每秒读取一次

# 运行主程序
if __name__ == "__main__":
    main()
